package com.liukai.todo_android.ui.activity;


import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;

import com.liukai.todo_android.R;
import com.liukai.todo_android.broadcastReceiver.CountDownBroadcastReceiver;
import com.liukai.todo_android.call_back.IFindTodoCallBack;
import com.liukai.todo_android.common.base.BaseActivity;
import com.liukai.todo_android.common.utils.Constants;
import com.liukai.todo_android.common.utils.JSONUtil;
import com.liukai.todo_android.common.utils.LogUtils;
import com.liukai.todo_android.entity.ItemVo;
import com.liukai.todo_android.entity.Resp;
import com.liukai.todo_android.presenter.FindSchedulePresenter;
import com.liukai.todo_android.service.CountDownService;
import com.liukai.todo_android.ui.dialog.ModifyTimingTypeDialog;
import com.liukai.todo_android.ui.dialog.SaveConcentrationDialog;
import com.liukai.todo_android.ui.dialog.listener.ModifySuccessListener;
import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;

import butterknife.BindView;

public class ConcentrationActivity extends BaseActivity implements
        CountDownBroadcastReceiver.UpdateCountListener,
        IFindTodoCallBack, ModifySuccessListener {

    @BindView(R.id.btn_start)
    AppCompatButton btnStart;
    @BindView(R.id.ticker_view)
    TickerView tickerView;
    @BindView(R.id.item_name)
    TextView itemName;
    @BindView(R.id.item_desc)
    TextView itemDesc;
    @BindView(R.id.btn_back)
    TextView btnBack;
    @BindView(R.id.btn_reset)
    AppCompatButton btnReset;
    @BindView(R.id.btn_stop)
    AppCompatButton btnStop;
    private Context context;
    private ItemVo itemVo = null;
    private boolean mBound;

    public static final int STATUS_STOP = 1;
    public static final int STATUS_PAUSE = 2;
    public static final int STATUS_START = 3;
    public static final int STATUS_RESET = 4;
    /**
     * 开始按钮状态，默认是停止
     */
    public int btnStartStatus = STATUS_STOP;
//    private int timingType;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            CountDownService.MyBinder binder = (CountDownService.MyBinder) iBinder;
            service = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };
    private CountDownService service;
    private Intent intent;
    private CountDownBroadcastReceiver countDownBroadcastReceiver;
    private ModifyTimingTypeDialog dialog;
    private AlertDialog.Builder builder;
    private AlertDialog warningDialog;
    private SaveConcentrationDialog saveConcentrationDialog;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_concentration;
    }

    @Override
    protected void initData(Context _context) {

        context = _context;
        Intent intent = getIntent();
        if (intent != null) {
            itemVo = (ItemVo) intent.getSerializableExtra(Constants.ITEM_VO_KEY);
        }
        registerReceiver();
        if (itemVo.getTimingType() == Constants.TIMING_TYPE_NO) {
            openModifyTimingTypeDialog(itemVo);
            return;
        }
    }

    @Override
    protected void initView() {
        tickerView.setCharacterList(TickerUtils.getDefaultListForUSCurrency());
        setTextView(itemVo);
        tickerView.setAnimationDuration(500);
        tickerView.setAnimationInterpolator(new OvershootInterpolator());
        createWarningDialog();
        initDialog();
    }

    private void initDialog() {
        saveConcentrationDialog = new SaveConcentrationDialog(context, itemVo);
        saveConcentrationDialog.setModifySuccessListener(this);
    }

    /**
     * 设置倒计时文本框的初始值
     */
    private void setTextView(ItemVo itemVo) {
        if (itemVo.getTimingType() == Constants.TIMING_TYPE_UP) {
            tickerView.setText("00:00:00");
        }
        if (itemVo.getTimingType() == Constants.TIMING_TYPE_DOWN) {
            tickerView.setText(getDateTime(itemVo.getConsumePlanning()));
        }
        if (itemVo.getTimingType() == Constants.TIMING_TYPE_NO) {
            tickerView.setText("");
        }
        itemName.setText(itemVo.getTitle());
        itemDesc.setText(itemVo.getDescription());
    }

    @Override
    protected void initListener() {
        btnStart.setOnClickListener(v -> {
            if (btnStartStatus == STATUS_STOP) {
                bindService();
            } else if (btnStartStatus == STATUS_START) {
                intent.putExtra(Constants.COUNT_DOWN_STATUS_KEY, STATUS_PAUSE);
                startService(intent);
            } else if (btnStartStatus == STATUS_PAUSE) {
                intent.putExtra(Constants.COUNT_DOWN_STATUS_KEY, STATUS_START);
                startService(intent);
            }
            btnStop.setVisibility(View.VISIBLE);
            resetBtnStartStatus();
        });
        btnBack.setOnClickListener(v -> {
            if (warningDialog.isShowing()) {
                warningDialog.dismiss();
                return;
            }
            warningDialog.show();
        });
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopConcentration();
            }

        });
    }

    /**
     * 结束专注
     */
    private void stopConcentration() {
        intent.putExtra(Constants.COUNT_DOWN_STATUS_KEY, STATUS_STOP);
        saveConcentrationDialog.show();
        startService(intent);
    }

    /**
     * 重置计时
     */
    private void reset() {
        setTextView(itemVo);
        intent.putExtra(Constants.COUNT_DOWN_STATUS_KEY, STATUS_START);
        startService(intent);
    }

    /**
     * 打开修改倒计时类型的对话框
     *
     * @param itemVo
     */
    private void openModifyTimingTypeDialog(ItemVo itemVo) {
        dialog = new ModifyTimingTypeDialog(context, itemVo);
        dialog.setModifySuccessListener(this);
    }

    private void getItem() {
        FindSchedulePresenter findSchedulePresenter = new FindSchedulePresenter();
        findSchedulePresenter.registerCallback(this);
        findSchedulePresenter.getOneItem(itemVo);
    }

    /**
     * 绑定服务
     */
    private void bindService() {
        intent = createIntent();
        startService(intent);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 创建intent
     *
     * @return
     */
    private Intent createIntent() {
        Intent intent = new Intent(this, CountDownService.class);
        intent.putExtra(Constants.COUNT_DOWN_TIME_KEY, itemVo.getConsumePlanning());
        intent.putExtra(Constants.COUNT_DOWN_STATUS_KEY, STATUS_START);
        int type = itemVo.getTimingType();
        intent.putExtra(Constants.TIMING_TYPE_KEY, type);
        return intent;
    }

    /**
     * 动态注册广播
     */
    private void registerReceiver() {
        // 注册广播，实时接收服务传递回来的数据
        countDownBroadcastReceiver = new CountDownBroadcastReceiver();
        countDownBroadcastReceiver.setUpdateCountListener(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.COUNT_DOWN_BROADCAST_RECEIVER);
        registerReceiver(countDownBroadcastReceiver, filter);
    }

    /**
     * 广播中返回的新的倒计时时间
     *
     * @param newSting
     */
    @Override
    public void updateCountDown(String newSting, boolean isStop) {
        if (isStop) {
            saveConcentrationDialog.show();
            return;
        }
        LogUtils.e(getClass(), newSting + "<==========>Activity22222");
        tickerView.setText(newSting);
    }

    /**
     * 重新设置开始按钮的状态
     */
    private void resetBtnStartStatus() {
        switch (btnStartStatus) {
            case STATUS_PAUSE:
                btnStartStatus = STATUS_START;
                btnStart.setText("开始");
            case STATUS_STOP:
                btnStartStatus = STATUS_START;
                btnStart.setText("暂停");
                break;
            case STATUS_START:
                btnStartStatus = STATUS_PAUSE;
                btnStart.setText("继续");
                break;
            default:
        }
    }

    @Override
    protected void release() {
        unregisterReceiver(countDownBroadcastReceiver);
        if (mBound) {
            stopService(intent);
            unbindService(mServiceConnection);
            mBound = false;
        }
        ConcentrationActivity.this.finish();
    }

    /**
     * 根据计划时间获取时分秒格式的字符串
     *
     * @param consumePlanning
     * @return
     */
    private String getDateTime(int consumePlanning) {
        String hh = String.valueOf(consumePlanning / 60 / 60 % 60);
        String mm = String.valueOf(consumePlanning / 60 % 60);
        String ss = String.valueOf(consumePlanning % 60);

        if (hh.length() == 1) {
            hh = "0" + hh;
        }
        if (mm.length() == 1) {
            mm = "0" + mm;
        }
        if (ss.length() == 1) {
            ss = "0" + ss;
        }
        return hh + ":" + mm + ":" + ss;
    }

    @Override
    public void findScheduleSuccess(Resp resp) {
        itemVo = JSONUtil.resolverResult(resp, ItemVo.class);
        setTextView(itemVo);
        dialog.dismiss();
    }

    @Override
    public void findScheduleError(Resp resp) {

    }

    @Override
    public void onBackPressed() {
        if (warningDialog.isShowing()) {
            warningDialog.dismiss();
            return;
        }
        warningDialog.show();
    }

    /**
     * 创建警告对话框
     */
    private void createWarningDialog() {
        builder = new AlertDialog.Builder(context);
        builder.setTitle("注意!");
        builder.setMessage("退出专注页面，专注会停止并且不会保存记录");
        builder.setCancelable(false);
        builder.setPositiveButton("取消退出", (dialog, which) -> warningDialog.dismiss());
        builder.setNegativeButton("保存后退出", (dialog, which) -> {

        });
        builder.setNeutralButton("继续退出", (dialog, which) -> {
            warningDialog.dismiss();
            ConcentrationActivity.this.finish();
        });
        warningDialog = builder.create();
    }

    @Override
    public void modifySuccess() {
        getItem();
    }

    @Override
    public void cancel() {
        ConcentrationActivity.this.finish();
    }

    @Override
    public void saveSummarySuccess() {
        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
        ConcentrationActivity.this.finish();
    }
}